<script setup>
import { ref, onMounted, reactive, getCurrentInstance } from "vue";
// import { getCommentListApi, postAddCommentApi } from "@/api/common";
// import PageQuery from "@/components/common/PageQuery.vue";
import ChildComment from "@/components/ChildComment.vue";
// import { useUserStore } from "@/stores/useUserStore";
// import ChildComment from "@/components/ChildComment.vue";
import { commentAddService, commentSelectService, commentDeleteService } from '@/api/comment'
import { inject } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
// import { useUserInfoStore } from "@/store/user";

const instance = getCurrentInstance();  // 获取当前实例
const $imageUrlPre = instance.appContext.config.globalProperties.$imageUrlPre;

// const userStore = useUserInfoStore()

const route = useRoute()
const solutionId = route.query.solutionId

// const { userInfo } = useUserStore();
const userInfo = ref({
  avatar: '',
});
// 收集 “编辑区” 的输入内容
const comment = ref("");
// 收集 “回复框” 的输入内容
const replyComment = ref("");
// 存储请求回来的数据总数
const total = ref(0);
// 存储请求回来的留言列表
const commentsList = ref([
  {
    commentId: '', // 对应数据库字段 commentId
    userImg: '',
    user_id: '', // 对应数据库字段 user_id
    roleName: '',
    commentContent: '', // 对应数据库字段 commentContent
    create_time: '', // 对应数据库字段 create_time
    reply_id: '', // 对应数据库字段 reply_id
    children: [
      {
        user_id: '',
        commentContent: '',
        create_time: '',
      }
    ]
  }
]);
// 控制回复框的索引
const showReplyIndex = ref(0);
// 控制回复框的显示隐藏
const showReply = ref(false);
//要回复的对方姓名
const replyName = ref('');

const titleId = ref()

titleId.value = inject('titleId')
console.log(titleId.value)

onMounted(() => {

  getCommentList();
});

// 接收父组件传过来的值——在别的文件中使用留言组件，则改文件为留言组件的父组件
const props = defineProps({
  // 关联主体ID
  momentId: {
    type: Number,
    required: true,
  },
  postAddCommentForm: {
    type: Object,
    required: true,
  },
});

// 请求当前主体的评论列表
const getCommentForm = reactive({
  pageNum: 1,
  pageSize: 10,
  momentId: props.momentId,
});

/**
 * 获取留言列表
 */
const getCommentList = async () => {
  try {
    // 封装参数
    const res = await commentSelectService(solutionId);
    if (res.data.status === 'success') {
      commentsList.value = res.data.data.list;
      console.log(commentsList.value)
    } else {
      ElMessage.error(res.data.info)
    }
    // total.value = res.data.total;
  } catch (error) { }
};

/**
 * 显示 回复编辑框
 */
// const handleReply = (commentId, pCommentId,name) => {
//   console.log(commentId)
//   console.log(pCommentId)
//   // console.log(pCommentId)
//   if(pCommentId == -1){
//     pCommentId = commentId//如果回复的没有父id，则发表评论的父级id就为该id
//     showReplyIndex.value = commentId;
//     replyName.value = ''
//   }else{
//     showReplyIndex.value = pCommentId;
//     replyName.value = name
//   }
//   showReply.value = !showReply.value;
//   // console.log("showReplyIndex = " + showReplyIndex.value)
//   // console.log("showReply = " + showReply.value)

//   setTimeout(() => {
//     const replyBox = document.querySelector(".reply-box-container");
//     console.log(replyBox)
//     if(!replyBox)return
//     replyBox.setAttribute("data-parent-comment-id", pCommentId);
//     replyBox.setAttribute("data-reply-comment-id", commentId);
//   },200)
// };

/**
 * 发布/回复 评论
 */
// const handlePublish = async () => {
//   const params = {
//     commentContent: comment.value, // 使用 commentContent 替代 comment
//     solutionId: solutionId, // 对应数据库的 solutionId
//     rootCommentId: 1, // 根评论 ID 对应 commentId
//     pCommentId: -1, // 父评论 ID 对应 pCommentId
//     userId: userStore.userInfo.userId,
//     replyId: -1,
//     // replyComment: replyComment.value,
//   };

//   // 子评论添加属性
//   const replyBox = document.querySelector(".reply-box-container");
//   if (replyBox) {
//     let pCommentId = Number(replyBox.getAttribute("data-parent-comment-id"));
//     let replyId = Number(replyBox.getAttribute("data-reply-comment-id"));
//     // if(pCommentId == -1){
//       //   pCommentId = replyId
//       // }

//       // params.commentId = commentId;
//     params.commentContent = replyComment.value
//     params.pCommentId = pCommentId;
//     params.replyId = replyId;
//   } 
//   console.log(params);
//   // 发送请求
//   try {
//     const res = await commentAddService(params);
//     if(res.data.status === 'success'){
//       ElMessage.success('发布评论成功');
//       comment.value = ''
//       replyComment.value = ''
//       // replyComment.value = ''
//     }else{
//       ElMessage.error(res.data.info)
//     }

//     getCommentList();
//     // commentsList.value.push(params);
//   } catch (error) {
//     console.log("🚀 ~ handlePublish ~ error:", error);
//   }
// };

/**
 * 分页器--当前页的数据量
 */
const handlePageSize = (pageSizeVal) => {
  getCommentForm.pageSize = pageSizeVal.pageSize;
  getCommentList();
};

/**
 * 分页器--切换页码
 */
const handlePageNum = (pageNumVal) => {
  getCommentForm.pageNum = pageNumVal.pageNum;
  getCommentList();
};

/**
 * 删除评论
 */
const deleteComment = async (commentId) => {
  ElMessageBox.confirm(
    '确定要删除该评论吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await commentDeleteService(commentId)
      if(res.data.status === 'success'){
        ElMessage.success('删除成功')
        getCommentList()
      }else{
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })
}
</script>

<template>
  <div class="comments">
    <el-card>
      <template #header>
        <div class="comments-header">
          <h3>留言区</h3>
        </div>
      </template>

      <!-- 编辑区 -->
      <!-- <div class="editbox">
        <div class="editbox-left">
          <el-avatar :size="45" :src="$imageUrlPre + userStore.userInfo.avatar" />
        </div>
        <div class="editbox-middle">
          <el-input
            placeholder="与其赞同别人的话语，不如自己畅所欲言..."
            v-model="comment"
          ></el-input>
        </div>
        <div class="editbox-right">
          <el-button @click="handlePublish">发布</el-button>
        </div>
      </div> -->

      <!-- 列表区 -->
      <div class="listbox" v-for="(item, index) in commentsList" :key="index">
        <!-- 顶级留言 -->
        <div class="top-level">
          <div class="listbox-top-user">
            <el-avatar :size="45" :src="$imageUrlPre + item.avatar" />
            <p>
              <span>{{ item.name }}</span>
              <!-- <span>{{ item.userId }}</span> -->
              <!-- <span>回复</span> -->
              <!-- <span>李四</span> -->
            </p>
          </div>
          <div class="listbox-middle-root">{{ item.commentContent }}
            <el-button style="float: right" type="danger" @click="deleteComment(item.commentId)">删除</el-button>
          </div> <!-- 对应 commentContent -->
          <div class="listbox-bottom">
            <span>发布时间：{{ item.createTime }}</span> <!-- 对应 create_time -->
            <!-- <span @click="handleReply(item.commentId, item.pCommentId,item.name)">回复</span> 对应 commentId 和 pCommentId -->
          </div>
        </div>

        <!-- 子留言区 -->
        <div v-if="item.children && item.children.length">
          <ChildComment :ChildComments="item.children" @handle-reply="handleReply" style="margin-left: 0" />
        </div>

        <!-- 回复框 -->
        <div class="reply-box-container" v-if="showReplyIndex === item.commentId && showReply">
          <div class="replybox" id="reply-box">
            <div class="replybox-left">
              <el-avatar :size="30" :src="userInfo.avatar" />
            </div>
            <div class="replybox-middle">
              <el-input :placeholder="'回复' + replyName + '：'" v-model="replyComment"></el-input>
            </div>
            <div class="replybox-right">
              <el-button @click="handlePublish">提交</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页器 -->
      <!-- <PageQuery
        :total="total"
        :pageNum="getCommentForm.pageNum"
        :pageSize="getCommentForm.pageSize"
        @page-size="handlePageSize"
        @page-num="handlePageNum"
      /> -->
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
// 留言区
.comments {
  margin-top: 30px;
  margin-bottom: 100px;

  .el-card {
    width: 80%;
    margin: 20px auto;
  }

  .editbox,
  .listbox {
    margin: 0px 20px 20px 20px;
    display: flex;
  }

  // 编辑区
  .editbox {
    justify-content: space-between;
    align-items: center;

    .editbox-middle {
      width: 85%;
    }
  }

  // 列表展示区
  .listbox {
    flex-direction: column;
    border-bottom: 1px solid rgb(189, 187, 187);

    // 时间 + 回复
    .listbox-bottom {
      font-size: 12px;
      color: #9499a0;
      margin: 10px 0 10px 65px;
      display: flex;

      span {
        display: block;
        margin-right: 20px;
      }

      span:last-child:hover {
        cursor: pointer;
      }
    }

    // 信息条
    .listbox-top-user {
      display: flex;

      p {
        margin-left: 20px;
        width: 100%;
        position: relative;

        // span:first-child {
        //   color: $second-text;
        // }

        span:nth-of-type(2) {
          margin-left: 5px;
          margin-right: 5px;
          // font-size: 8px;
          // padding: 2px;
          color: rgb(101, 153, 237);
          border-radius: 5px;
          // position: absolute;
        }
      }
    }

    // 顶级评论
    .top-level {
      .listbox-middle-root {
        margin-left: 65px;
      }
    }

    // 回复评论输入框
    .replybox {
      margin: 10px 0 20px 65px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 60%;

      .replybox-middle {
        width: 75%;
      }
    }

    // 展示更多
    .view-more {
      margin-left: 65px;
      font-size: 12px;
      color: #9499a0;
    }

    .view-more span:hover,
    .view-less span:hover {
      cursor: pointer;
    }

    // 展示更少
    .view-less {
      font-size: 12px;
      color: #9499a0;
      margin-left: 37px;
    }
  }
}
</style>
